package com.cml;

import com.cml.handler.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 姓名：陈茂林
 * 时间：2024/4/2
 * 描述：
 */
public class Client implements Lifecycle{
    EventLoopGroup eventLoopGroup ;
    Bootstrap bootstrap;

    ChannelFuture channelFuture;
    private Logger logger = LogManager.getLogger(Client.class);
    private String  host;
    private int port;

    public Client(String host,int port){
        this.host=host;
        this.port=port;
        this.init();
    }
    @Override
    public void init() {
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new ClientHandler());
                    }
                });
    }

    @Override
    public void start() {
        try {
            channelFuture = bootstrap.connect(host, port).sync();
        } catch (InterruptedException e) {
            logger.error(e);
        }
    }

    public void sendMsg(){
        String msg = (String) IntStream.rangeClosed(0, 1000)
                .boxed()
                .map(Object::toString).collect(Collectors.joining(","));

        String msg2 = "qwertyuiop";
        ByteBuf buffer = Unpooled.buffer(4+msg.length()+4+msg2.length());
        buffer.writeInt(msg.length());
        buffer.writeBytes(msg.getBytes());
        buffer.writeInt(msg2.length());
        buffer.writeBytes(msg2.getBytes());
        channelFuture.channel().writeAndFlush(buffer);
        channelFuture.channel().flush();
    }

    @Override
    public void close() {
        try {
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error(e);
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
